import 'package:flutter/material.dart';
import 'package:flutter_base/http/api.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/http/http_manager.dart';
import 'package:flutter_base/pages/order/model/model_order_tags.dart';

import 'package:flutter_base/pages/order/order_list/order_list_view.dart';
import 'package:flutter_base/widgets/tab/common_tab_bar_page.dart';
import 'package:get/get.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';

class OrderLogic extends BaseController with GetSingleTickerProviderStateMixin {
  late TabController tabController;

  // 所有订单列表
  List<ModelOrderTags> allOrders = [
    ModelOrderTags(name: 'MBTI'),
  ];

  // 心理测试类型列表
  List<ModelOrderTags> psychologyTypes = [];

  // 选项卡列表
  List<CommonTabModel> get orderList => psychologyTypes.isNotEmpty
      ? psychologyTypes
          .map((e) => CommonTabModel(
              title: e.name ?? '',
              view: OrderListPage(typeId: (e.id ?? '').toString())))
          .toList()
      : allOrders
          .map((e) => CommonTabModel(
              title: e.name ?? '',
              view: OrderListPage(typeId: (e.id ?? '').toString())))
          .toList();

  @override
  void onInit() {
    super.onInit();
    // tabController = TabController(length: orderList.length, vsync: this);
    // tabController.addListener(() {
    //   if (tabController.indexIsChanging) {
    //     update();
    //   }
    // });
  }

  @override
  void onReady() {
    super.onReady();
    loadPsychologyTypes();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }

  // 加载心理测试类型
  Future<void> loadPsychologyTypes() async {
    doLoading();
    HttpResponse response = await HttpManager().get(
      API.psychologyTypes,
      params: {
        'page': 1,
        'size': 100,
      },
      fromJson: ModelOrderTags.fromJson,
      uiType: HttpUIType.none, // 静默加载，不显示UI提示
    );

    if (response.isSuccess) {
      psychologyTypes = response.data;
    } else {
      psychologyTypes = allOrders;
    }
    tabController = TabController(length: orderList.length, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        update();
      }
    });
    doFinished();
  }

  // 标签切换事件
  void onTabChanged(int index) {
    update();
  }
}
